import Vue from 'vue'
import router from '@/router'
import axios from 'axios'
import {clearLoginInfo} from '@/utils'
import api from '@/utils/api'
import qs from 'qs'
import merge from 'lodash/merge'

const http = axios.create({
 // baseURL: 'http://tp6admin.com',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})
//请求拦截
http.interceptors.request.use(config => {


  //请求地址的处理
  (process.env.NODE_ENV == 'development') ? (() => {
    config.url = '/proxyApi' + api[config.url]
  })() : (() => {
    config.url =  api[config.url]
  })();
  //请求参数的处理
  let defaults = {
    't': new Date().getTime()
  }
  let option = null
  switch (config.method) {
    case 'get':
      option = merge(defaults, config.params)
      config.params = option
      break
    case 'post':
      option = merge(defaults, config.data)
      config.data = config.contentType ? qs.toString(option) : JSON.stringify(option)
      break
  }
  let t = Vue.cookie.get('admin')
  if (t) {
    t = JSON.parse(t)
    config.headers['token'] = t.token//请求头带上token
  }
  return config

}, error => {
  return Promise.reject(error)
})
//响应拦截
http.interceptors.response.use(res => {
  if (res.data && res.data.code == 401) {
    clearLoginInfo()
    router.push({name: 'login'})
  }
  return res.data
}, err => {
  return err
})

export default http
